package com.study.testSpringBoot.concurrent;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.springframework.stereotype.Component;

/**
 * 使用ConcurrentHashMap的数据模型
 * 使用lock锁可以实现
 */
@Component
public class DataModelLock {

	private ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
	
	private Lock lock = new ReentrantLock();
	
	public void addData(String key) {
		try {
			lock.tryLock(3, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		lock.lock();
		try {
			int num = 1;
			if(map.containsKey(key)) {
				num = map.get(key) + 1;
			}
			map.put(key, num);
		} finally {
			lock.unlock();
		}
	}
	
	public Map<String,Integer> getAndDelData() {
		lock.lock();
		try {
			Map<String,Integer> m = new HashMap<>();
			Set<Entry<String,Integer>> set = map.entrySet();
			for(Entry<String,Integer> entry : set) {
				m.put(entry.getKey(), entry.getValue());
			}
			map.clear();
			return m;
		} finally {
			lock.unlock();
		}
	}
	
}
